% To remove spikes in time series
% latest date 18.4.3
function[TS] = despike(TS,ProcDef),
Step =8;
Win = 10;

A = size(TS.matrix);

for j = 1:A(2),
   p=1;
   for i = 1:Step:(A(1)-Step),
      C(p) = std(TS.matrix(i:i+Step,j));
      p=p+1;
   end;
   
   K = find(C>10*median(C));
   p = length(K);
   p = K(2:p)-K(1:p-1);
   p = find(p<3);
   K(p) = [];  % this deletes more than one points representing same spike
   
   
   for ii = 1:length(K),
      if K(ii)*Step-Win > 0 & K(ii)*Step+Win < A(1),
         CenSpk = (K(ii)*Step+Step/2);
         SpkData = TS.matrix(CenSpk-Win:CenSpk+Win,j);
         Inc = (SpkData(end)-SpkData(1))/(Win*2+1);
         if Inc == 0,
            TS.matrix(CenSpk-Win:CenSpk+Win+1,j) = SpkData(1);
         else,
            TS.matrix(CenSpk-Win:CenSpk+Win+1,j) =...
               floor(SpkData(1):Inc:SpkData(end));
            end;
      end;
   
end;

   
      
end;


